const fs = require("fs")
let className = require("./p4-module")
let CN = new className.CUser("lyshsd")

function home(response) {
    response.writeHead(200, {
        'Content-Type': "text/html"
    })
    fs.createReadStream(__dirname + "/index.html", "utf8").pipe(response)
    console.log("这是首页");
}

function renewCart(response) {
    response.writeHead(200, {
        'Content-Type': "text/html"
    })
    var readerStream = fs.createReadStream(CN.用户名 + '.txt')
    var writerStream1 = fs.createWriteStream(CN.用户名 + '/cart.txt');
    readerStream.pipe(writerStream1);
    fs.createReadStream(__dirname + "/renew.html", "utf8").pipe(response)
    console.log("用户更新了购物车，cart.txt创建成功");
}

function readCart(response) {
    response.writeHead(200, {
        'Content-Type': "application/json"
    })
    fs.createReadStream(__dirname + "/" + CN.用户名 + "/cart.txt", "utf8").pipe(response)
    console.log("用户读取了购物车");
}

function delUser(response) {
    var files = fs.readdirSync(CN.用户名); //读取该文件夹

    files.forEach(function(file) {

        var stats = fs.statSync(CN.用户名 + '/' + file);

        if (stats.isDirectory()) {

            emptyDir(CN.用户名 + '/' + file);

        } else {

            fs.unlinkSync(CN.用户名 + '/' + file);

            console.log("删除文件" + CN.用户名 + '/' + file + "成功");

        }

    })
    fs.rmdir(CN.用户名, function() {
        console.log("删除目录成功")
    })

    response.writeHead(200, {
        'Content-Type': "text/html"
    })
    fs.createReadStream("/del.html", "utf8").pipe(response)
    console.log("用户删除了");

}


module.exports = {
    home,
    renewCart,
    readCart,
    delUser

}